package com.xiaolin.thirtpart.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginController
 * @Description 第三方登录-以微博登录为例
 * @Detail    第三方登录基本步骤
 *                  1、用户访问网站的登录页面
 *                  2、用户点击微博登录，请求用户认证服务器
 *                  3、跳转到微博授权页
 *                  4、用户进行授权
 *                  5、用户授权成功后，请求回调接口
 *                  5、回调接口获取授权码，携带授权码请求认证服务器获取access_token
 *                  6、回调接口携带访问token请求资源服务器获取用户信息
 *                  7、保存或更新用户信息到用户表中
 *                  8、将用户信息保存到session或者token
 * @Author MyPC
 * @Date 2020/10/7
 * @Version 1.0
 */
@Controller
@RequestMapping("/auth")
public class LoginController {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${third.appkey}")
    private String appKey;
    @Value("${third.AppSecret}")
    private String appSecret;
    @Value("${third.redirectUri}")
    private String redirectUri;

    /**
     * 接收授权码、获取token和用户信息
     * @param code
     * @return
     */
    @RequestMapping("/access")
    public String loginAccess(@RequestParam("code") String code) throws UnsupportedEncodingException {
        String url="https://api.weibo.com/oauth2/access_token";
        MultiValueMap<String,String> params=new LinkedMultiValueMap<>();
        params.add("client_id",appKey);
        params.add("client_secret",appSecret);
        params.add("grant_type","authorization_code");
        params.add("redirect_uri",redirectUri);
        params.add("code",code);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

        // 1、获取token信息
        JSONObject body = restTemplate.postForEntity(url, request, JSONObject.class).getBody();
        String access_token = body.getString("access_token");
        String uid = body.getString("uid");
        // 2、获取用户信息
        Map userInfo = restTemplate.getForObject("https://api.weibo.com/2/users/show.json?access_token="+access_token+"&uid="+uid, Map.class);
        System.out.println(userInfo);
        return "index";
    }
}
